import React from 'react'
import { BaseListPage, IBaseListPageState, IBaseListPageProps, uaaApp, columnRenders, UdPage, UdPageHeader, UdFilter, UdTable, UdToolbar, UdModal, UdModalForm, http, UdDateRangePicker, IListQueryParams, UdDatePicker } from '@/lib'
import StateSwitchBtn from '@/components/StateSwitchBtn'
import { Button, Table, Badge, Tabs, Input, BackTop, Affix, message, Modal, Upload, Select, DatePicker, Spin } from 'antd'
import classNames from 'classnames'
import _ from 'lodash'
import ButtonGroup from 'antd/lib/button/button-group'
import apis from '@/apis/AboutQuota'
import MyModel from './components/UdModel'
import CurrentMonthPinModel from './components/CurrentMonthPinModel'
import { downBlobFile } from '@/utils/methods'
import './comm.css'
import dayjs from 'dayjs'
import { EDealerType } from '../../AdjustTheRecord/List'
import { TableColumns, EListType, queryUrls, switchTypes } from './config.options'



const { TabPane } = Tabs;
const { Option } = Select;
let brandCode = JSON.parse(sessionStorage.getItem("UaaSysInfo"))?.profile?.brandCode[0]
let setFlowReqVos = []
const postBtnAuth = 'quota_employee_manager_quotaTransmit'
const exportBtn = 'quota_employee_manager_quotaTransmitExport'
const importBtn = 'quota_employee_manager_quotaTransmitImport'
const DetailBtnAuth = 'user_domainandproduct_manager_list'
const dateFormat = 'YYYY-MM-DD';

const exportUrlsEnum = {
  [EListType.AREA_CUSTOMER_TYPE]: apis.QuotaAreaCusExport,
  [EListType.AREA_TYPE]: apis.QuotaAreaExport,
  [EListType.MATERIAL_CLASS_TYPE]: apis.QuotaMatClassExport,
}

export default class MonthlyQuotaAllocationList extends BaseListPage<MonthlyQuotaAllocationListProps, MonthlyQuotaAllocationListState> {
  private modal
  private listType = EListType.CUSTOMER_TYPE
  private tableColumns = {}
  private filterValues = {}
  constructor(props) {
    super(props)
    this.tableColumns = new TableColumns(this.handelDelete)
    this.state = {
      rowlist: [],
      rows: [],
      expendData: [],
      brandCode,
      brandCompanies: [],
      loading: false,
      title: '配额下达',
      queryApi: (value) => {
        this.filterValues = value
        const apiUrl = queryUrls[this.listType]
        return http.post(apiUrl, { ...value, brandCode: this.state.brandCode })
      },
      method: "POST",
      rowKey: 'id',
      conditions: [
        { id: 'dealerName', label: '客户名称' },
        // { id: 'inventoryBegineTime', label: '盘点周期' },
        { id: 'belongAreaName', label: '所属管理区域' },
        {
          id: 'sourceFrom', label: '数据来源', render: (text) => (
            <Select>
              <Select.Option value='SYSTEM'>系统取数</Select.Option>
              <Select.Option value='ARTIFICIAL'>手工导入</Select.Option>
            </Select>
          )
        },
      ],
      columns: this.tableColumns[this.listType],
      tableProps: {
        scroll: { x: true },
        // rowSelection: {},
        expandedRowRender: this.expandedRowRender
      },
      brandNames: [],
      visible: false,
      nextText: '下一步',
      current: 0,
      uploading: false,
      downLoading: false,
    }
  }
  componentDidMount() {
    super.componentDidMount()
    this.getBrandCompanyList()
  }
  private getBrandCompanyList = () => { //销售组织简称
    http.get(apis.getUserBrands).then(res => {
      const brandCompanies = res.data.map(({ brandCode: value, brandNameShort: title }) => ({ value, title }))
      // 过滤掉头曲二曲的
      const hideArr = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
      let brandfilter = brandCompanies.filter(item => hideArr.indexOf(item.title) === -1)
      this.setState({
        brandCompanies: brandfilter
      })
    })
  }

  /* 客户维度外层表格删除 */
  private handelDelete = (record) => { //第一层删除
    console.log(record.id);
    const rows = this.state.rows?.filter(item => item.id != record.id)
    this.setState({
      dataSource: this.state.dataSource.filter(item => item.id != record.id),
      rowlist: this.state.rowlist?.filter(item => item.id != record.id),
      rows,
    })
  }
  private expandedRowRender = (record, index, indent, expanded) => {
    if (!expanded) {
      return null
    }
    // 客户维度内嵌表格数据在quotaModifyHistoryRespVoList，其他在details
    const dataSource = record.quotaModifyHistoryRespVoList || record.details
    // 客户维度内嵌表格列
    let columns = [
      { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, reoder, index) => index + 1 },
      { title: '物料分类名称', dataIndex: 'groupName', key: 'groupName', minWidth: '200px', width: '20%' },
      {
        title: '当前动销/件',
        key: 'nowMove',
        dataIndex: 'nowMove',
        width: '104px',
        render: (text, record) => (
          <span>
            <a onClick={() => this.handelCurrentPin(record)}>{text}</a>
          </span>
        ),
      },
      { title: '理论配额值/件', dataIndex: 'quotaCountNum', key: 'quotaCountNum', width: '104px', render: (text) => <span>{text || 0}</span> },
      {
        title: '片区申请配额/件', dataIndex: 'oldQuotaNum', key: 'oldQuotaNum', width: '114px',
        render: (text) => text ? <span>{text}</span> : '0'
      },
      { title: '实际配额/件', dataIndex: 'quotaNum', key: 'quotaNum', width: 140 },

      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        // width: '80px',
        render: columnRenders.operate([
          {
            title: '删除', action: (text: any, record: any) => { this.handelDelite(record, index) }
          },
        ])
      },
    ];

    if (this.tableColumns[this.listType + '_SUB']) {
      // 其他维度内嵌表格列
      columns = this.tableColumns[this.listType + '_SUB']
    }

    return <Table columns={columns} dataSource={dataSource} pagination={false} rowKey='id' />;
  };

  /* 客户维度内嵌表格删除 */
  public handelDelite = (record, index) => {
    this.state.dataSource[index].quotaModifyHistoryRespVoList = this.state.dataSource[index].quotaModifyHistoryRespVoList.filter(item => item.id != record.id)
    const parentId = this.state.dataSource[index].id
    const rows = this.state.rows?.map(item => {
      if (item.id == parentId) {
        item.quotaModifyHistoryRespVoList = item.quotaModifyHistoryRespVoList.filter(mat => mat.id != record.id)
      }
      return item
    })
    this.setState({
      dataSource: this.state.dataSource,
      rows,
    })
  }

  render() {
    const { conditions } = this.state
    const showRowSelection = this.listType == EListType.CUSTOMER_TYPE
    return (
      <Spin spinning={this.state.uploading || this.state.downLoading} tip={this.state.uploading ? "上传中，请稍后..." : "请求中，请稍后..."}>
        <UdPage className="list-page">
          {
            this.state.title && <UdPageHeader title={this.state.title} subTitle={this.state.subTitle}
              onRefresh={this.query}
              affixProps={{ target: () => this.pageContainer }} />
          }
          {
            (_.isArray(conditions) && conditions.length > 0) && (
              <UdFilter
                loading={this.state.querying} items={conditions}
                getForm={(form) => { this.filterForm = form }}
                onSearch={this.handleSearch} resetAfter={this.filterReset}
              ></UdFilter>
            )
          }
          <Affix className="ud-page-toolbar-affix" offsetTop={40} target={() => this.pageContainer}>
            <UdToolbar other={
              <ButtonGroup>
                {(uaaApp.canUse(postBtnAuth) && showRowSelection) && <Button type='primary' onClick={() => this.examineAll()}>全部审核</Button>}
                {(uaaApp.canUse(postBtnAuth) && showRowSelection) && <Button type='primary' onClick={() => this.openModalHandle()}>提交审核</Button>}
                {(uaaApp.canUse(importBtn) && showRowSelection) && <Button type="primary" onClick={() => this.handeltolead()}>导入</Button>}
                {(uaaApp.canUse(exportBtn) && showRowSelection) && <Button type="primary" onClick={() => this.handeltolout()}>导出</Button>}
              </ButtonGroup>
            }>
            </UdToolbar>
          </Affix>
          {/* 品牌切换 */}
          <Tabs defaultActiveKey={brandCode} onChange={this.switchTodoTabHandle} type="card">
            {this.state.brandCompanies?.map(todoTab => (
              <TabPane tab={todoTab.title} key={todoTab.value} />
            ))}
          </Tabs>
          {/* 维度切换 */}
          <Tabs activeKey={this.listType} onChange={this.switchListTypeHandle}>
            {switchTypes?.map(type => (
              <TabPane tab={type.title} key={type.value} />
            ))}
          </Tabs>
          <div className="types-table" key={this.listType}>
            <UdTable loading={this.state.querying} rowKey={this.state.rowKey}
              pagination={this.state.pagination} {...this.state.tableProps}
              columns={this.state.columns} dataSource={this.state.dataSource}
              onChange={this.handleTableChange}
              rowSelection={showRowSelection ? {
                onChange: this.onSelectChange,
                selectedRowKeys: this.state.rowlist
              } : null}
            />
          </div>
          {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
        </UdPage>
      </Spin>
    )
  }

  /* 品牌切换 */
  private switchTodoTabHandle = (key) => {
    this.listType = EListType.CUSTOMER_TYPE // 初始化维度
    this.queryParams.page = 1 // 重置分页
    this.setState({ brandCode: key, rowlist: [], rows: [] }, () => {
      this.query()
    })

  }

  /* 维度切换 */
  private switchListTypeHandle = (key) => {
    this.listType = key
    const tableProps = { ...this.state.tableProps }
    if (this.listType == EListType.AREA_CUSTOMER_TYPE) {
      // 片区+客户维度，没有内嵌表格
      tableProps.expandedRowRender = null
    } else {
      tableProps.expandedRowRender = this.expandedRowRender
    }
    this.queryParams.page = 1 // 重置分页
    this.setState({ columns: this.tableColumns[this.listType], tableProps })
    this.query()
  }

  private onSelectChange = (rowlist, rows) => {
    this.setState({
      rowlist,
      rows
    })
  }

  private examineAll = () => {
    if (!this.state.dataSource.length) return
    this.props.history.push({ pathname: `/quota/monthlyquota/editer/0/0`, state: { brandCode: this.state.brandCode, filterValues: this.filterValues } })
  }

  private openModalHandle = () => {
    const { rows, rowlist } = this.state
    if (rowlist.length == 0) {
      message.warning('请选择你要审核的内容')
    } else {
      let value = JSON.stringify(rows)
      // 储存选择的行数据，审核操作页获取数据操作
      sessionStorage.setItem('checkedList', value)
      // let times = dayjs(rows[0].inventoryBegineTime).format('YYYY年MM月')
      let times = rows[0].description || dayjs(rows[0].quotaModifyHistoryRespVoList[0].quotaStartTime).format('YYYY年MM月')

      const {brandCode, brandName} = rows[0]
      this.props.history.push({
        pathname: `/quota/monthlyquota/editer/${times}/${brandName}?brandCode=${brandCode}&brandName=${brandName}`
      })
    }

  }

  private handelCurrentPin = (record) => {
    let brandCode = record.brandCode
    let dealerCode = record.dealerCode
    let productGroupId = record.productGroupId
    UdModal.open({
      title: '本月动销',
      width: 800,
      content: <CurrentMonthPinModel
        brandCode={brandCode}
        dealerCode={dealerCode}
        groupId={productGroupId}
      />
    })
  }
  private handeltolead = () => {//导入
    this.modal = UdModal.open({
      title: '批量导入',
      width: 300,
      content: <>
        <div className='import-user-modal'>
          <Button type='primary' onClick={this.downloadTpl}>下载模板</Button>
          <Upload showUploadList={false} customRequest={this.importUser}><Button type='primary'>导入配额</Button></Upload>
        </div>
      </>,
      footer: null,
      maskClosable: false,
      centered: true,
    })
  }
  private importUser = (option) => {
    this.modal && this.modal.destroy()
    this.setState({ uploading: true })
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    http.post(apis.quotaTransmitImport, formData, { timeout: 1000 * 60 * 10 }).then(res => {
      message.success('上传成功')
      this.query()
    }).finally(() => this.setState({ uploading: false }))
  }

  private downloadTpl = () => {
    http.post(apis.TemplateExport, {}, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '配额下达导入模板')
      }
    }).catch((err) => { console.log(err) })
  }

  private handeltolout = () => { //导出
    if (this.listType == EListType.CUSTOMER_TYPE) {
      let newrow = this.state.rows.map(item => {
        let resp = item.quotaModifyHistoryRespVoList.map(resp => {
          resp.code = resp.productGroupId
          resp.realityQuotaNum = resp.quotaNum
          resp.inventoryCycle = resp.description
          return resp
        })
        return resp
      }).flat(Infinity)
      this.downloadExcel(apis.quotaTransmitExport, newrow, '配额下达列表')
    } else {
      const url = exportUrlsEnum[this.listType]
      const params = this.queryParams.conditions
      // 维度名称
      const typeTitle = switchTypes.find(type => type.value == this.listType)?.title || ''
      this.downloadExcel(url, params, `配额下达列表${typeTitle}`)
    }
  }

  private downloadExcel = (url, params, fileName) => {
    if (this.state.rows.length != 0 || this.listType != EListType.CUSTOMER_TYPE) {
      // 客户维度需要选择导出行数据
      this.setState({ downLoading: true })
      let idList = []
      this.state.rows.map(item => {
        idList.push(item.id)
      })
      http.post(url, Object.assign({
        brandCode,
        idList
      }, this.queryParams.conditions), { responseType: 'arraybuffer' }).then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, fileName)
        }
      }).finally(() => {
        this.setState({ downLoading: false })
      })
    } else {
      // message.warning('请选择要导出的内容！')
      // 导出逻辑切换为,没有选择数据就导出全部数据
      if (this.state.dataSource.length == 0) {
        message.warning('没有要导出的内容！')
        return
      }
      this.setState({ downLoading: true })
      http.post(url, Object.assign({ status: 'ALL', brandCode }, this.queryParams.conditions), { responseType: 'arraybuffer' }).then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, fileName)
        }
      }).finally(() => {
        this.setState({ downLoading: false })
      })
    }
  }
}



interface MonthlyQuotaAllocationListState extends IBaseListPageState {
  brandNames: any,
  visible: boolean,
  nextText: string,
  current: number | string,
  uploading: boolean,
  expendData: any,
  brandCode: string,
  rowlist: any,
  rows: any,
  loading: boolean,
  downLoading: boolean,
  brandCompanies: any
}

interface MonthlyQuotaAllocationListProps extends IBaseListPageProps {

}
